package szcg.main.service.api;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import szcg.framework.library.base.PostController;
import szcg.framework.library.utils.Md5Utils;
import szcg.framework.library.utils.TimeUtils;

import java.util.HashMap;


@RestController
@RequestMapping(value = "/main", produces = {"application/json;charset=UTF-8"})
public class MAIN_000_000_000 extends PostController {

    public MAIN_000_000_000() {

    }

    //session接口
    @PostMapping(value = "/000_000_000")
    public String doPost(HttpServletRequest request) {
        return handleRequest(request);
    }

    @Override
    protected String postRequest(HashMap<String, String> param) {
        String requestBody = param.get("requestBody");
        if (requestBody == null || requestBody.isEmpty()) {
            return generateFail("请求body为空");
        }
        //解析json
        JSONObject jsonObject = (JSONObject) JSON.parse(requestBody);
        String timestamp = jsonObject.getString("timestamp");
        String issue = jsonObject.getString("issue");
        String version = jsonObject.getString("version");
        String channel = jsonObject.getString("channel");
        String author = jsonObject.getString("author");
        String permission = jsonObject.getString("permission");
        String signature = jsonObject.getString("signature");
        //验证时间戳（前后不超过2分钟）
        long timeDifference = TimeUtils.calculate(Long.parseLong(timestamp), System.currentTimeMillis());
        long limit = 1000 * 60 * 2;
        if (Math.abs(timeDifference) > limit) {
            //时间戳超时了
            return generateFail("timestamp超时");
        }
        //签名按照顺序channel->version->author->permission->issue全小写再md5
        String s = timestamp.toLowerCase() + channel.toLowerCase() + version.toLowerCase() + author.toLowerCase() + permission.toLowerCase() + issue.toLowerCase();
        String dynamicSignature = Md5Utils.generateMD5(s);
        if (signature == null || !signature.equals(dynamicSignature)) {
            return generateFail("无效signature");
        }
        //封装响应体
        HashMap<String, String> resMap = new HashMap<>();
        resMap.put("sessionId", generateSessionId());
        return generateSucceed(resMap);
    }
}
